package cn.edu.nju.software.action.book;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import cn.edu.nju.software.bean.show.BookShow;
import cn.edu.nju.software.bean.show.CategoryShow;
import cn.edu.nju.software.bean.storage.Book;
import cn.edu.nju.software.service.intf.BookService;
import cn.edu.nju.software.util.Constants;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class GetBooksAction extends ActionSupport implements SessionAware {

	private boolean searchAccurate;
	private String isbn;
	private String title;
	private String author;
	private String publisher;
	private Date beginDate;
	private Date endDate;
	private int category;
	private BookService bookService;
	private Map<String, Object> session;

	public void setSearchAccurate(boolean searchAccurate) {
		this.searchAccurate = searchAccurate;
	}

	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public void setPublisher(String publisher) {
		this.publisher = publisher;
	}

	public void setBeginDate(Date beginDate) {
		this.beginDate = beginDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public void setCategory(int category) {
		this.category = category;
	}

	public int getCategory() {
		return category;
	}

	public void setBookService(BookService bookService) {
		this.bookService = bookService;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	private void storeIntoSession(String name, List<Book> books) {
		Map<Integer, BookShow> booksMap = new LinkedHashMap<Integer, BookShow>(books.size());
		@SuppressWarnings("unchecked")
		Map<Integer, CategoryShow> allCategories = (Map<Integer, CategoryShow>) session.get(Constants.SESSION_ALL_CATEGORIES);
		for(Book book : books) {
			booksMap.put(book.getBookID(), new BookShow(book, allCategories.get(book.getCategoryID())));
		}
		books = null;
		session.put(name, booksMap);
	}
	
	public String searchFront() throws Exception {
		if (isbn==null && title==null && author==null && publisher==null && beginDate==null && endDate==null && category<=0) {
			return INPUT;
		}
		List<Book> books;
		if (searchAccurate) {
			books = bookService.searchBooks(isbn, null, null, null, null, null, 0);
		} else {
			books = bookService.searchBooks(null, title, author, publisher, beginDate, endDate, category);
		}
		storeIntoSession(Constants.SESSION_BOOKS, books);
		return SUCCESS;
	}
	
	public String getAll() throws Exception {
		storeIntoSession(Constants.SESSION_BOOKS_ADMIN, bookService.getAllBooks());
		return SUCCESS;
	}
	
}
